<template>
    <div class="page-container">
        <div class="header">
            <h1>商品管理 {{ currentStoreName ? `- ${currentStoreName}` : '' }}</h1>
            <div class="header-actions">
                <div class="search-container">
                    <input type="text" v-model="searchQuery" placeholder="搜索商品名称...">
                </div>
                <button class="btn" @click="addProduct" v-if="currentStoreId">添加商品</button>
            </div>
        </div>

        <div v-if="loading" class="loading-state">正在加载商品...</div>
        <div v-if="error" class="error-state">{{ error }}</div>

        <div v-if="filteredProducts" class="table-container">
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>商店ID</th>
                        <th>商品信息</th>
                        <th>分类</th>
                        <th>价格</th>
                        <th>库存</th>
                        <th>销量</th>
                        <th>推荐</th>
                        <th>新品</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="product in filteredProducts" :key="product.productId">
                        <td>
                            <span>{{ product.productId }}</span>
                        </td>
                        <td>
                            <span>{{ product.storeId }}</span>
                        </td>
                        <td>
                            <img :src="product.mainImage || defaultImage" alt="商品图片" class="product-image">
                            <span>{{ product.name }}</span>
                        </td>
                        <td>{{ getCategoryName(product.categoryId) }}</td>
                        <td>¥{{ (product.price || 0).toFixed(2) }}</td>
                        <td>{{ product.stock || 0 }}</td>
                        <td>{{ product.salesCount || 0 }}</td>
                        <td>{{ product.isFeatured ? '是' : '否' }}</td>
                        <td>{{ product.isNew ? '是' : '否' }}</td>
                        <td>
                            <a href="#" class="action-btn" @click.prevent="editProduct(product)">编辑</a>
                            <a href="#" class="action-btn delete"
                                @click.prevent="deleteProduct(product.productId)">删除</a>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <!-- Edit Product Modal -->
        <div v-if="isModalVisible" class="modal-overlay" @click.self="cancelEdit">
            <div class="modal-content">
                <h2>{{ isEditMode ? '编辑商品' : '添加商品' }}</h2>
                <form @submit.prevent="saveProduct">
                    <div class="form-group">
                        <label for="name">商品名称 <span class="required">*</span></label>
                        <input type="text" id="name" v-model="editableProduct.name" 
                               :class="{'input-error': formErrors.has('name')}"
                               @input="clearFieldError('name')">
                    </div>
                    <div class="form-group">
                        <label for="description">描述</label>
                        <textarea id="description" v-model="editableProduct.description"></textarea>
                    </div>
                    <div class="form-group">
                        <label for="category">分类 <span class="required">*</span></label>
                        <select id="category" v-model="editableProduct.categoryId" 
                                :class="{'input-error': formErrors.has('category')}"
                                @change="clearFieldError('category')">
                            <option v-for="cat in categories" :key="cat.categoryId" :value="cat.categoryId">
                                {{ cat.name }}
                            </option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>产品规格 <span class="required">*</span></label>
                        <div v-for="(spec, index) in specValueList" :key="index" class="spec-input-group">
                            <input type="text" v-model="specValueList[index]" 
                                   placeholder="例如：250g/盒，500ml/瓶" 
                                   class="spec-input" 
                                   :class="{'input-error': formErrors.has('spec')}"
                                   @input="clearFieldError('spec')">
                            <button type="button" class="btn-icon" @click="removeSpec(index)" v-if="specValueList.length > 1">-</button>
                        </div>
                        <button type="button" class="btn-secondary btn-small" @click="addSpec">+ 添加规格</button>
                    </div>
                    <div class="form-group form-group-inline">
                        <div>
                            <label for="price">价格 <span class="required">*</span></label>
                            <input type="number" id="price" v-model.number="editableProduct.price" step="0.01"
                                   :class="{'input-error': formErrors.has('price')}"
                                   @input="clearFieldError('price')">
                        </div>
                        <div>
                            <label for="salePrice">促销价</label>
                            <input type="number" id="salePrice" v-model.number="editableProduct.salePrice" step="0.01">
                        </div>
                        <div>
                            <label for="stock">库存 <span class="required">*</span></label>
                            <input type="number" id="stock" v-model.number="editableProduct.stock"
                                   :class="{'input-error': formErrors.has('stock')}"
                                   @input="clearFieldError('stock')">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="mainImage">主图</label>
                        <div class="image-upload-wrapper">
                            <img :src="editableProduct.mainImage || defaultImage" alt="商品主图" class="image-preview">
                            <input type="file" id="mainImageUpload" @change="handleImageUpload" accept="image/*"
                                style="display: none;">
                            <label for="mainImageUpload" class="btn btn-secondary">选择图片</label>
                        </div>
                    </div>
                    <div class="form-group form-group-inline">
                        <div class="checkbox-group">
                            <input type="checkbox" id="isFeatured" v-model="editableProduct.isFeatured" :true-value="1"
                                :false-value="0">
                            <label for="isFeatured">是否推荐</label>
                        </div>
                        <div class="checkbox-group">
                            <input type="checkbox" id="isNew" v-model="editableProduct.isNew" :true-value="1"
                                :false-value="0">
                            <label for="isNew">是否新品</label>
                        </div>
                    </div>
                    <div class="modal-actions">
                        <button type="button" class="btn btn-secondary" @click="cancelEdit">取消</button>
                        <button type="submit" class="btn" :disabled="isSaving">保存</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue';
import { useRoute } from 'vue-router';
import { api } from '@/network/api';
import { ElMessage } from 'element-plus';

interface Category {
    categoryId: number;
    name: string;
}

interface Product {
    productId: number;
    storeId: number;
    categoryId: number;
    name: string;
    description: string;
    mainImage: string;
    price: number;
    salePrice?: number;
    stock: number;
    isFeatured: number;
    isNew: number;
    salesCount: number;
    specValueList?: string[];
    specValue?: string;
}

interface Store {
    storeId: number;
    name: string;
}

const route = useRoute();
const products = ref<Product[]>([]);
const loading = ref(true);
const error = ref<string | null>(null);
const defaultImage = '/avatar/avatar.png';
const categories = ref<Category[]>([]);
const categoryMap = new Map<number, string>();
const currentStoreId = ref<number | null>(null);
const currentStoreName = ref<string | null>(null);
const searchQuery = ref('');

const isModalVisible = ref(false);
const isEditMode = ref(false);
const editableProduct = ref<Partial<Product>>({});
const isSaving = ref(false);
const specValueList = ref<string[]>(['']);
const formErrors = ref<Set<string>>(new Set());

const filteredProducts = computed(() => {
    if (!products.value) return [];
    if (!searchQuery.value) {
        return products.value;
    }
    const lowerCaseQuery = searchQuery.value.toLowerCase();
    return products.value.filter(product =>
        product.name.toLowerCase().includes(lowerCaseQuery) ||
        product.description.toLowerCase().includes(lowerCaseQuery)
    );
});

const fetchProducts = async () => {
    try {
        loading.value = true;
        let response;

        if (currentStoreId.value) {
            // 获取特定商店的商品
            response = await api.getStoreProducts(currentStoreId.value);
        } else {
            // 获取所有商品
            response = await api.getProductsListByMemberLevel();
        }

        console.log('商品数据响应:', response);

        // 检查数据结构并正确处理
        if (response && response.data && Array.isArray(response.data)) {
            // 直接使用返回的数组
            products.value = response.data;
        } else if (response && response.data && Array.isArray(response.data.data)) {
            // 嵌套在data字段中的数组
            products.value = response.data.data;
        } else {
            console.error('无法识别的数据结构:', response);
            products.value = [];
        }

        error.value = null;
    } catch (err) {
        console.error("获取商品列表失败:", err);
        error.value = '商品列表加载失败，请稍后重试。';
    } finally {
        loading.value = false;
    }
};

const getStoreInfo = async (storeId: number) => {
    try {
        const response = await api.getStoreDetail(storeId);
        if (response.data && response.data.data) {
            currentStoreName.value = response.data.data.name;
        }
    } catch (err) {
        console.error("获取商店信息失败:", err);
    }
};

const getCategoryName = (categoryId: number) => {
    return categoryMap.get(categoryId) || 'N/A';
};

const fetchCategories = async () => {
    try {
        const response = await api.getCategories();
        categories.value = response.data.data;
        categoryMap.clear();
        if (categories.value) {
            categories.value.forEach(category => {
                categoryMap.set(category.categoryId, category.name);
            });
        }
    } catch (err) {
        console.error("获取分类列表失败:", err);
    }
};

const handleImageUpload = (event: Event) => {
    const target = event.target as HTMLInputElement;
    if (target.files && target.files[0]) {
        const file = target.files[0];
        const reader = new FileReader();
        reader.onload = (e) => {
            if (e.target && e.target.result) {
                editableProduct.value.mainImage = e.target.result as string;
            }
        };
        reader.readAsDataURL(file);
    }
};

const addSpec = () => {
    specValueList.value.push('');
};

const removeSpec = (index: number) => {
    specValueList.value.splice(index, 1);
};

const addProduct = () => {
    isEditMode.value = false;
    specValueList.value = [''];
    editableProduct.value = {
        name: '',
        description: '',
        categoryId: categories.value.length ? categories.value[0].categoryId : 0,
        price: 0,
        salePrice: 0,
        stock: 0,
        mainImage: '',
        isFeatured: 0,
        isNew: 0,
        storeId: currentStoreId.value || 0,
    };
    isModalVisible.value = true;
};

const editProduct = (product: Product) => {
    isEditMode.value = true;
    editableProduct.value = { ...product };
    
    if (product.specValueList && product.specValueList.length > 0) {
        specValueList.value = [...product.specValueList];
    } else if (product.specValue) {
        specValueList.value = [product.specValue];
    } else {
        specValueList.value = [''];
    }
    
    // 确保数值型字段不为null
    editableProduct.value.salesCount = editableProduct.value.salesCount || 0;
    editableProduct.value.stock = editableProduct.value.stock || 0;
    editableProduct.value.price = editableProduct.value.price || 0;
    editableProduct.value.salePrice = editableProduct.value.salePrice || 0;
    
    isModalVisible.value = true;
};

const validateForm = (): boolean => {
    // 清空之前的错误
    formErrors.value.clear();
    
    // 收集所有验证错误
    const errors: string[] = [];
    
    // 验证商品名称
    if (!editableProduct.value.name || editableProduct.value.name.trim() === '') {
        errors.push('请输入商品名称');
        formErrors.value.add('name');
    }
    
    // 确保数值型字段不为null
    editableProduct.value.price = editableProduct.value.price || 0;
    editableProduct.value.stock = editableProduct.value.stock || 0;
    editableProduct.value.salesCount = editableProduct.value.salesCount || 0;
    editableProduct.value.salePrice = editableProduct.value.salePrice || 0;
    
    // 验证价格
    if (!editableProduct.value.price || editableProduct.value.price <= 0) {
        errors.push('请输入有效的商品价格');
        formErrors.value.add('price');
    }
    
    // 验证分类
    if (!editableProduct.value.categoryId) {
        errors.push('请选择商品分类');
        formErrors.value.add('category');
    }
    
    // 验证库存
    if (editableProduct.value.stock === undefined || editableProduct.value.stock < 0) {
        errors.push('请输入有效的商品库存');
        formErrors.value.add('stock');
    }
    
    // 验证规格：至少需要一个有效的规格
    const validSpecs = specValueList.value.filter(spec => spec.trim() !== '');
    if (validSpecs.length === 0) {
        errors.push('请至少添加一个有效的商品规格');
        formErrors.value.add('spec');
    } else {
        editableProduct.value.specValueList = validSpecs;
    }
    
    // 设置商店ID
    if (!editableProduct.value.storeId && currentStoreId.value) {
        editableProduct.value.storeId = currentStoreId.value;
    }
    
    // 如果有错误，显示所有错误
    if (errors.length > 0) {
        if (errors.length === 1) {
            ElMessage.error(errors[0]);
        } else {
            ElMessage({
                message: `表单有 ${errors.length} 个必填项未完成:<br>${errors.map(err => `• ${err}`).join('<br>')}`,
                type: 'error',
                dangerouslyUseHTMLString: true,
                duration: 5000
            });
        }
        return false;
    }
    
    return true;
};

const saveProduct = async () => {
    if (!validateForm()) return;

    try {
        isSaving.value = true;
        if (isEditMode.value) {
            // 更新现有商品
            if (!editableProduct.value.productId) return;
            await api.updateProduct(editableProduct.value);
            ElMessage({
                message: '商品更新成功！',
                type: 'success',
                duration: 2000
            });
        } else {
            // 创建新商品
            await api.createProduct(editableProduct.value);
            ElMessage({
                message: '商品添加成功！商品已成功上架。',
                type: 'success',
                duration: 2000
            });
        }

        isModalVisible.value = false;
        await fetchProducts(); // 刷新商品列表
    } catch (err: any) {
        console.error(isEditMode.value ? "更新商品失败:" : "添加商品失败:", err);
        let errorMsg = isEditMode.value ?
            '商品更新失败！' :
            '商品添加失败！';

        // 尝试从API错误响应中提取具体错误信息
        if (err.response && err.response.data && err.response.data.message) {
            errorMsg += ' ' + err.response.data.message;
        } else {
            errorMsg += '请检查输入信息或网络连接。';
        }

        ElMessage({
            message: errorMsg,
            type: 'error',
            duration: 4000
        });
    } finally {
        isSaving.value = false;
    }
};

const cancelEdit = () => {
    isModalVisible.value = false;
};

const deleteProduct = async (id: number) => {
    try {
        if (confirm(`确定要删除商品 ID: ${id} 吗? 此操作不可恢复。`)) {
            loading.value = true; // 显示加载状态
            await api.deleteProduct(id);
            ElMessage({
                message: '商品删除成功！',
                type: 'success',
                duration: 2000
            });
            await fetchProducts(); // 刷新商品列表
        }
    } catch (err: any) {
        console.error('删除商品失败:', err);
        let errorMsg = '商品删除失败！';

        // 尝试从API错误响应中提取具体错误信息
        if (err.response && err.response.data && err.response.data.message) {
            errorMsg += ' ' + err.response.data.message;
        } else {
            errorMsg += '请检查网络连接或联系管理员。';
        }

        ElMessage({
            message: errorMsg,
            type: 'error',
            duration: 4000
        });
    } finally {
        loading.value = false;
    }
};

// 清除特定字段的错误
const clearFieldError = (field: string) => {
    formErrors.value.delete(field);
};

// 监听路由变化
watch(() => route.params.storeId, async (newStoreId) => {
    if (newStoreId) {
        currentStoreId.value = parseInt(newStoreId as string);
        await getStoreInfo(currentStoreId.value);
    } else {
        currentStoreId.value = null;
        currentStoreName.value = null;
    }
    await fetchProducts();
}, { immediate: true });

onMounted(() => {
    fetchCategories();
});
</script>

<style scoped>
.page-container {
    padding: 30px;
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.header h1 {
    font-size: 2em;
    margin: 0;
}

.header-actions {
    display: flex;
    align-items: center;
    gap: 20px;
}

.search-container input {
    width: 300px;
    padding: 10px 15px;
    font-size: 1em;
    border-radius: 6px;
    border: 1px solid #ddd;
    transition: box-shadow 0.2s, border-color 0.2s;
}

.search-container input:focus {
    outline: none;
    border-color: #3498db;
    box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
}

.btn {
    background-color: #3498db;
    color: white;
    padding: 10px 18px;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    text-decoration: none;
    font-size: 1.2em;
    transition: background-color 0.3s;
}

.btn:hover {
    background-color: #2980b9;
}

.table-container {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
    overflow: hidden;
}

table {
    width: 100%;
    border-collapse: collapse;
}

th,
td {
    padding: 15px 20px;
    text-align: left;
    border-bottom: 1px solid #f0f0f0;
    vertical-align: middle;
}

th {
    background-color: #f8f9fa;
    font-size: 1.2em;
    color: #555;
}

td {
    font-size: 1.2em;
}

tr:last-child td {
    border-bottom: none;
}

.product-image {
    width: 60px;
    height: 60px;
    object-fit: cover;
    border-radius: 6px;
    vertical-align: middle;
    margin-right: 15px;
}

.action-btn {
    color: #3498db;
    text-decoration: none;
    margin-right: 15px;
}

.action-btn:hover {
    text-decoration: underline;
}

.action-btn.delete {
    color: #e74c3c;
}

.loading-state,
.error-state {
    padding: 20px;
    text-align: center;
    color: #666;
}

.modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.6);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.modal-content {
    background: white;
    padding: 25px 30px;
    border-radius: 8px;
    width: 90%;
    max-width: 600px;
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
    max-height: 90vh;
    overflow-y: auto;
}

.modal-content h2 {
    margin-top: 0;
    margin-bottom: 20px;
}

.form-group {
    margin-bottom: 15px;
}

.form-group label {
    display: block;
    margin-bottom: 5px;
    font-weight: 500;
}

.form-group input[type="text"],
.form-group input[type="number"],
.form-group textarea,
.form-group select {
    width: 100%;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 4px;
    box-sizing: border-box;
}

.form-group textarea {
    min-height: 80px;
    resize: vertical;
}

.form-group-inline {
    display: flex;
    gap: 15px;
}

.form-group-inline>div {
    flex: 1;
}

.checkbox-group {
    display: flex;
    align-items: center;
    gap: 8px;
}

.checkbox-group input[type="checkbox"] {
    width: auto;
}

.image-upload-wrapper {
    display: flex;
    align-items: center;
    gap: 15px;
}

.image-preview {
    width: 80px;
    height: 80px;
    border-radius: 4px;
    object-fit: cover;
    border: 1px solid #ddd;
}

.modal-actions {
    margin-top: 25px;
    text-align: right;
}

.modal-actions .btn {
    margin-left: 10px;
}

.btn-secondary {
    background-color: #6c757d;
    color: white;
    padding: 10px 15px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

.btn-secondary:hover {
    background-color: #5a6268;
}

.spec-input-group {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
}

.spec-input {
    flex: 1;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 4px;
    box-sizing: border-box;
}

.btn-icon {
    background-color: #e74c3c;
    color: white;
    border: none;
    border-radius: 4px;
    width: 30px;
    height: 30px;
    font-size: 16px;
    margin-left: 8px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
}

.btn-small {
    padding: 5px 10px;
    font-size: 0.9em;
    margin-top: 8px;
}

.required {
    color: red;
    font-size: 0.8em;
    margin-left: 5px;
}

.input-error {
    border: 1px solid #e74c3c !important;
    box-shadow: 0 0 5px rgba(231, 76, 60, 0.3);
}
</style>